import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test01/config/config.dart';
import 'package:test01/model/user_model.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({Key? key}) : super(key: key);

  @override
  _RegisterScreenState createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  String _username = "";
  String _password = "";
  bool _allowLogin = false;
  UserModelItem _user = new UserModelItem();
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  _changeAllowLogin() {
    if (_username != "" &&
        _username != null &&
        _password != "" &&
        _password != null) {
      setState(() {
        _allowLogin = true;
      });
    }
  }

  _checkUserExist() async {
    var api = "${Config.domain}user/checkUserExist?username=$_username";
    var result = await Dio().get(api);
    return result.data;
  }

   _register() async {
    var api = "${Config
        .domain}user/insertUser?username=$_username&&password=$_password";
    var result = await Dio().get(api);
    var userModel = UserModel.fromJson(result.data!);
    if (userModel.status == 200) {
      _user = userModel.data!;
    }
    return userModel;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Text(""),
        elevation: 0,
        centerTitle: true,
        backgroundColor: Colors.white,
        title:
        Text("注册", style: TextStyle(fontSize: 30.w, color: Colors.black87)),
      ),
      body: Container(
        color: Colors.white,
        height: double.infinity,
        child: ListView(
          children: [
            Container(
              margin: EdgeInsets.only(left: 30.w, top: 80.h),
              height: 100.h,
              child: Text(
                "使用用户名和密码注册",
                style: TextStyle(fontSize: 45.w, color: Colors.black87),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 52.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                      bottom: BorderSide(width: 2.h, color: Colors.black26))),
              child: Row(children: [
                Container(
                  margin: EdgeInsets.only(left: 20.w),
                  color: Colors.white,
                  height: 56.h,
                  width: 100.w,
                  child: Text("用户名",
                      style: TextStyle(fontSize: 30.w, color: Colors.black87)),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 30.w),
                    child: TextField(
                      onChanged: (value) {
                        _username = value;
                        _changeAllowLogin();
                      },
                      cursorColor: Colors.black,
                      cursorHeight: 56.h,
                      decoration: InputDecoration(
                          hintText: "请输入用户名",
                          hintStyle:
                          TextStyle(fontSize: 30.w, color: Colors.black26),
                          border: InputBorder.none),
                    ),
                  ),
                )
              ]),
            ),
            Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                      bottom: BorderSide(width: 2.h, color: Colors.black26))),
              child: Row(children: [
                Container(
                  margin: EdgeInsets.only(left: 20.w),
                  color: Colors.white,
                  height: 56.h,
                  width: 100.w,
                  child: Text("密码",
                      style: TextStyle(fontSize: 30.w, color: Colors.black87)),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 30.w),
                    child: TextField(
                      onChanged: (value) {
                        _password = value;
                        if (value.length >= 6) {
                          _changeAllowLogin();
                        }
                        if (value.length < 6) {
                          setState(() {
                            _allowLogin = false;
                          });
                        }
                      },
                      obscureText: true,
                      cursorColor: Colors.black,
                      cursorHeight: 56.h,
                      decoration: InputDecoration(
                          hintText: "请输入密码",
                          hintStyle:
                          TextStyle(fontSize: 30.w, color: Colors.black26),
                          border: InputBorder.none),
                    ),
                  ),
                )
              ]),
            ),
            Container(
              margin: EdgeInsets.only(top: 35.h, left: 35.w),
              alignment: Alignment.centerLeft,
              child: const Text("已有账号？ 点击进行登录"),
            ),
            Container(
              padding: EdgeInsets.only(top: 35.h),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pushNamed(context, "/login");
                    },
                    child: Container(
                      alignment: Alignment.center,
                      child: const Text("登录"),
                      width: 200.w,
                    ),
                    style: ElevatedButton.styleFrom(primary: Colors.lightGreen),
                  ),
                  ElevatedButton(
                    onPressed: _allowLogin == false
                        ? null
                        : () {
                          Future<dynamic> req = _register();
                          req.then((value) {
                            if (value.status == 200) {
                              _prefs.then((value) {
                                value.setInt("userId", _user.userId!);
                                Navigator.pushNamed(context, "/");
                              });
                            }
                            else {
                              showDialog(
                                context: context,
                                builder: (context) {
                                  return AlertDialog(
                                    title: Container(
                                        alignment: Alignment.center,
                                        child: Text(value.msg!,
                                          style: TextStyle(fontSize: 30.w),)
                                    ),
                                    actions: [
                                      Container(
                                        alignment: Alignment.center,
                                        child: OutlinedButton(onPressed: () {
                                          Navigator.pop(context);
                                        }, child: const Text("确定", style: TextStyle(
                                            color: Colors.lightGreen
                                        ),)),
                                      )
                                    ],
                                  );
                                },
                              );
                            }
                          });

                    },
                    child: Container(
                      alignment: Alignment.center,
                      child: const Text("注册"),
                      width: 200.w,
                    ),
                    style: ElevatedButton.styleFrom(primary: Colors.lightGreen),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
